package com.ying.user.service.impl;

import com.ying.user.dao.MmPermissionDao;
import com.ying.user.dao.MmRoleDao;
import com.ying.user.dao.MmUserDao;
import com.ying.user.entity.MmPermission;
import com.ying.user.entity.MmRole;
import com.ying.user.entity.MmUser;
import com.ying.user.entity.dto.MmUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MmUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private MmUserDao mmUserDao;

    @Autowired
    private MmRoleDao mmRoleDao;

    @Autowired
    private MmPermissionDao mmPermissionDao;

    @Override
    public UserDetails loadUserByUsername(String telephone) throws UsernameNotFoundException {
        MmUser mmUser = mmUserDao.findByTelephone(telephone)
                .orElseThrow(() -> new UsernameNotFoundException("未找到用户信息 : " + telephone));

        List<MmRole> roleList = mmRoleDao.selectByUserId(mmUser.getId());
        List<Long> roleIds = roleList.stream()
                .map(MmRole::getId)
                .collect(Collectors.toList());
        List<MmPermission> permissionList = mmPermissionDao.selectByRoleIdList(roleIds);
        return MmUserDetails.create(mmUser, roleList, permissionList);
    }
}